package com.wang.hello.qrcode;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.xwork2.ActionSupport;

public class QrCodeAction extends ActionSupport
{
	private static final long serialVersionUID = -2662603889144785315L;
	public transient final Log logger = LogFactory.getLog(getClass());

	private int width = 256;
	private int height = 256;
	private String code;
	
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		try {
			this.code = java.net.URLDecoder.decode(code, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}
	}
	
	public int getWidth() {
		return width;
	}
	public void setWidth(int width) {
		this.width = width;
	}
	public int getHeight() {
		return height;
	}
	public void setHeight(int height) {
		this.height = height;
	}
	public String getContentType()
	{
		return "image/png";
	}
	
	public void validate()
	{
		if(this.getCode().length() == 0)
			addFieldError( "form.message", "Code must not be empty!." );
	}
	
	public byte[] getQrCodeInBytes()
	{
		Barcode barcode = new QrCode(width, height);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		barcode.encoder(baos, code);
		return baos.toByteArray();
	}

	public String execute(){
		return SUCCESS;
	}
}
